package com.elai.baseconfig.service.impl;

import java.util.*;
import com.elai.common.utils.StringUtils;
import com.elai.baseconfig.domain.*;
import com.elai.baseconfig.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elai.baseconfig.mapper.EventItemMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 事件项目Service业务层处理
 *
 * @author elai
 * @date 2021-04-03
 */
@Service
public class EventItemServiceImpl implements EventItemService
{
    @Autowired
    private EventItemMapper eventItemMapper;
    @Autowired
    private EventMethodService eventMethodService;
    @Autowired
    private EventTypeService eventTypeService;
    @Autowired
    private BaseUserAttributesService baseUserAttributesService;

    @Autowired
    private EventTeamService eventTeamService;

    @Autowired
    private com.elai.baseconfig.service.ApplicationEventService applicationEventService;
    @Autowired
    private com.elai.baseconfig.service.ApplicationAttributeService applicationAttributeService;
    /**
     * 查询事件项目
     *
     * @param id 事件项目ID
     * @return 事件项目
     */
    @Override
    public EventItemDO selectEventItemById(Long id)
    {
        return eventItemMapper.selectEventItemById(id);
    }

    /**
     * 查询事件项目列表
     *
     * @param eventItem 事件项目
     * @return 事件项目
     */
    @Override
    public List<EventItemDO> selectEventItemList(EventItemDO eventItem)
    {
        return eventItemMapper.selectEventItemList(eventItem);
    }

    /**
     * 新增事件项目
     *
     * @param eventItem 事件项目
     * @return 结果
     */
    @Override
    public int insertEventItem(EventItemDO eventItem)
    {
        return eventItemMapper.insertEventItem(eventItem);
    }

    /**
     * 修改事件项目
     *
     * @param eventItem 事件项目
     * @return 结果
     */
    @Override
    public int updateEventItem(EventItemDO eventItem)
    {
        return eventItemMapper.updateEventItem(eventItem);
    }

    /**
     * 批量删除事件项目
     *
     * @param ids 需要删除的事件项目ID
     * @return 结果
     */
    @Override
    public int deleteEventItemByIds(Long[] ids)
    {
        return eventItemMapper.deleteEventItemByIds(ids);
    }

    /**
     * 删除事件项目信息
     *
     * @param id 事件项目ID
     * @return 结果
     */
    @Override
    public int deleteEventItemById(Long id)
    {
        return eventItemMapper.deleteEventItemById(id);
    }

    @Override
    public List selectEventItemsGroup(EventItemDO eventItem) {
        List<EventItemDO> list= eventItemMapper.selectEventItemsGroup(eventItem);
        List<Map<String,List>> ResultList=new ArrayList<Map<String,List>>();
        List<EventMethodDO> methodList=eventMethodService.selectEventMethodList(new EventMethodDO());
        for(EventItemDO eitem : list){
            String str=eitem.getEventMethod();
            Map itemMap=new HashMap();
            itemMap.put("value",eitem.getEventItemCode());
            itemMap.put("label",eitem.getEventItemName());
            List<Map<String,String>> childList=new ArrayList<Map<String,String>>();
            if(StringUtils.isNotEmpty(str)){
                String ids[]=str.split(",");
                for(String id:ids){
                    if("NaN".equals(id))continue;
                    EventMethodDO m=methodList.stream().filter(p -> p.getId() == Long.parseLong(id)).findFirst().get();
                    if(m!=null){
                        Map childIitemMap=new HashMap();
                        childIitemMap.put("value",m.getMethodStr());
                        childIitemMap.put("label",m.getMethodName());
                        childList.add(childIitemMap);
                    }
                }
                itemMap.put("children",childList);
            }
            ResultList.add(itemMap);
        }

        return ResultList;
    }

    @Transactional
    @Override
    public List<ImportEventItemDO> importEventData(HashMap<String, List<ImportEventItemDO>> listHashMap,String teamId,String lesseeId) {
        List<ImportEventItemDO> eventItemDOList1=listHashMap.get("eventItemDOList1");
        List<ImportEventItemDO> eventItemDOList2=listHashMap.get("eventItemDOList2");
        List<ImportEventItemDO> dataList=listHashMap.get("userList");
        List<ImportEventItemDO> errorList=new ArrayList<ImportEventItemDO>();

        //删除事件基本属性
        eventItemMapper.deleteEventItemByLesseeId(lesseeId);
        //删除事件
        eventTypeService.deleteEventTypeByLesseeId(lesseeId);
        //删除用户属性
        baseUserAttributesService.deleteBaseUserAttributeByLesseeId(lesseeId);

        //第一步，导入全埋点
        if(eventItemDOList1!=null&&eventItemDOList1.size()>0){
            importEventType(eventItemDOList1,teamId,lesseeId);
            importEventItem(eventItemDOList1,lesseeId);
        }
        //第二步，导入自定义埋点
        if(eventItemDOList2!=null&&eventItemDOList2.size()>0){
            EventTeamDO teamParam=new EventTeamDO();
            teamParam.setLesseeId(lesseeId);
            teamParam.setTeamCode("custom");
            List<EventTeamDO> teamList= eventTeamService.selectEventTeamList(teamParam);
            if(teamList.size()>0){
                EventTeamDO team=teamList.get(0);
                importEventType(eventItemDOList2,String.valueOf(team.getId()),lesseeId);
                importEventItem(eventItemDOList2,lesseeId);
            }

        }
        //导入用户数据
        if(dataList!=null&&dataList.size()>0){
            importUserattribute(dataList,lesseeId);
        }
        return errorList;
    }

    //导入元事件
    private  void importEventType(List<ImportEventItemDO> dataList,String teamId,String lesseeId){
        HashMap<String,ImportEventItemDO> hashMap=new HashMap();
        for(ImportEventItemDO itemDO:dataList){
            hashMap.put(itemDO.getEventNameCode(),itemDO);
        }
        for (Map.Entry<String,ImportEventItemDO> entry : hashMap.entrySet()) {
            ImportEventItemDO itemDO=entry.getValue();
            EventTypeDO eventTypeDO=new EventTypeDO();
            eventTypeDO.setStatus("Y");
            eventTypeDO.setEventType(itemDO.getEventNameCode());
            eventTypeDO.setEventTypeName(itemDO.getEventName());
            eventTypeDO.setTeamId(teamId);
            eventTypeDO.setLesseeId(lesseeId);
            eventTypeService.insertEventType(eventTypeDO);
        }
    }

    //导入事件属性
    private  void importEventItem(List<ImportEventItemDO> dataList,String lesseeId){
        //删除全部

        HashMap<String,ImportEventItemDO> hashMap=new HashMap();
        for(ImportEventItemDO itemDO:dataList){
            EventItemDO item=new EventItemDO();
            //查询EventId
            EventTypeDO eventParam=new EventTypeDO();
            eventParam.setLesseeId(lesseeId);
            eventParam.setEventType(itemDO.getEventNameCode());
            List<EventTypeDO>  eventTypeList=eventTypeService.selectEventTypeList(eventParam);
            EventTypeDO eventTypeDO=null;
            if(eventTypeList.size()==0){
                System.out.println("错误：事件为空");
            }else{
                eventTypeDO= eventTypeList.get(0);
            }
            item.setEventId(eventTypeDO.getId());
            item.setEventItemCode(itemDO.getEventItemNameCode());
            item.setEventItemName(itemDO.getEventItemName());
            item.setEventType(itemDO.getEventNameCode());
            item.setStatus(itemDO.getStatus());

            //处理事件取值类型
            String dataType=itemDO.getDataType();

            if("STRING".equals(dataType)){
                item.setValueType("01");
            }else if ("NUMBER".equals(dataType)){
                item.setValueType("02");
            }else  if("DATETIME".equals(dataType)){
                item.setValueType("03");
            }else  if("BOOL".equals(dataType)){
                item.setValueType("04");
            }else  if("LIST".equals(dataType)){
                item.setValueType("05");
            }else{
                item.setValueType("01");
            }

            //处理事件函数
            String function = itemDO.getFunction();
            StringBuilder builder=new StringBuilder();
            if(!StringUtils.isEmpty(function)){
                String[]  funs=function.split(",");
                for(String s:funs){
                    if(!StringUtils.isEmpty(s)) {
                        EventMethodDO eventMethodDO = eventMethodService.selectEventMethodByStr(s);
                        builder.append(","+eventMethodDO.getId());
                    }
                }
                String sb=builder.toString();
                if(StringUtils.isNotEmpty(sb)){
                    sb=sb.substring(1);
                }
                item.setEventMethod(sb);
            }
            //创建工单编号
            eventItemMapper.insertEventItem(item);
        }
    }

    //导入用户数据
    private  void importUserattribute(List<ImportEventItemDO> dataList, String lesseeId){

        for(ImportEventItemDO itemDO:dataList){
            if(itemDO.getEventItemNameCode()==""||itemDO.getEventItemName()==""){
                return;
            }
            BaseUserAttributesDO baseUserAttributes=new BaseUserAttributesDO();
            baseUserAttributes.setAttributeName(itemDO.getEventItemNameCode());
            baseUserAttributes.setAttributeRemark(itemDO.getEventItemName());
            baseUserAttributes.setLesseeId(lesseeId);
            //处理事件取值类型
            String dataType=itemDO.getDataType();

            if("STRING".equals(dataType)){
                baseUserAttributes.setDataType("01");
            }else if ("NUMBER".equals(dataType)){
                baseUserAttributes.setDataType("02");
            }else  if("DATETIME".equals(dataType)){
                baseUserAttributes.setDataType("03");
            }else  if("BOOL".equals(dataType)){
                baseUserAttributes.setDataType("04");
            }else  if("LIST".equals(dataType)){
                baseUserAttributes.setDataType("05");
            }else{
                baseUserAttributes.setDataType("01");
            }

            baseUserAttributes.setReportFlag("Y");
            baseUserAttributes.setPreSetFlag("Y");
            baseUserAttributes.setDictionaryFlag("Y");
            baseUserAttributes.setDisplayFlag("Y");
            //创建工单编号
            baseUserAttributesService.insertBaseUserAttributes(baseUserAttributes);
        }
    }

    @Override
    public List<EventItemDO> selectEventItemByType(EventItemDO eventItem) {
        return eventItemMapper.selectEventItemByType(eventItem);
    }
}
